package com.cyx.netty.gateway;

import com.cyx.netty.gateway.config.NettyHttpServer;
import com.cyx.netty.gateway.handler.predicate.RoutePredicates;
import com.cyx.netty.gateway.route.Routes;
import com.cyx.netty.gateway.route.CachingRouteLocator;
import com.cyx.netty.gateway.route.CompositeRouteLocator;
import com.cyx.netty.gateway.route.RouteLocator;
import java.util.List;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Flux;

@SpringBootApplication
public class GatewayNettyApplication {

	@Bean
	public RouteLocator customRouteLocator() {
		return Routes.locator()
				.route("get")
				.order(2)
				.uri("http://127.0.0.1:8977")
				.predicate(RoutePredicates.path("/get"))
				.and()
				.route("image")
				.order(999)
				.uri("http://httpbin.org:80")
				.predicate(RoutePredicates.path("/image/png"))
				.and()
				.build();
	}
	/**
	 * 创建一个缓存路由的路由定位器
	 * @param routeLocators
	 * @return
	 */
	@Bean
	@Primary//在相同的bean中，优先使用用@Primary注解的bean.
	public RouteLocator routeLocator(List<RouteLocator> routeLocators) {
		//1.创建组合路由定位器，根据(容器)已有的路由定位器集合
		//2.创建缓存功能的路由定位器
		return new CachingRouteLocator(new CompositeRouteLocator(Flux.fromIterable(routeLocators)));
	}

	public static void main(String[] args) {
	 SpringApplication.run(GatewayNettyApplication.class, args).getBean(NettyHttpServer.class).start();
	}

}
